package com.study.security.config;

import com.study.security.filter.SecurityAuthFilter;
import com.study.security.handler.AuthExceptionHandler;
import com.study.security.handler.AuthNotHandler;
import com.study.security.impl.UserDetailServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.firewall.DefaultHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    AuthExceptionHandler authExceptionHandler;

    @Autowired
    AuthNotHandler authNotHandler;

    @Autowired
    SecurityAuthFilter securityAuthFilter;

    @Autowired
    UserDetailServiceImpl userDetailServiceImpl;


    //不需要认证的地址
    private String[] noPermissions;


    public SecurityConfig(){
        List<String> list = new ArrayList<>();
        list.add("/sa/register");
        list.add("/sa/login");

        //swagger 不认证
        list.add("/swagger-ui.html");
        list.add("/swagger-resources/**");
        list.add("/webjars/**");
        list.add("/*/api-docs");
        noPermissions = list.toArray(new String[0]);
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        // 关闭scrf防护
        http.csrf()
                .disable()
                    //不使用session
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                    //认证过的用户访问无权限的资源异常
                    .exceptionHandling().accessDeniedHandler(authExceptionHandler)
                    //匿名用户访问资源异常
                    .authenticationEntryPoint(authNotHandler)
                .and()
                    //不需要认证的请求放过
                    .authorizeRequests().antMatchers(noPermissions).permitAll()
                    //其他请求都需要认证
                    .anyRequest().authenticated()
                .and().cors().and()
                    //自定义权限拦截器
                    .addFilterBefore(securityAuthFilter, UsernamePasswordAuthenticationFilter.class)
                //使用iframe拒绝访问
                .headers().frameOptions().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder(){

        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return StringUtils.equals(charSequence,s);
            }
        };
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 自定义认证
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.userDetailServiceImpl).passwordEncoder(passwordEncoder());
    }


    @Bean
    public HttpFirewall httpFirewall() {
        return new DefaultHttpFirewall();
    }
}
